package com.tianzeculture.stagebao.activity.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tianzeculture.stagebao.R;
import com.tianzeculture.stagebao.application.StageBaoApplication;
import com.tianzeculture.stagebao.base.BaseActivity;
import com.tianzeculture.stagebao.bean.User;
import com.tianzeculture.stagebao.dialog.ChoiceJobDialog;
import com.tianzeculture.stagebao.dialog.PhotoDialog;
import com.tianzeculture.stagebao.dialog.SexDialog;
import com.tianzeculture.stagebao.net.UserRestUsage;
import com.tianzeculture.stagebao.network.Request;
import com.tianzeculture.stagebao.network.enity.MSG;
import com.tianzeculture.stagebao.network.util.ToastUtil;
import com.tianzeculture.stagebao.popwindow.CityPickerPopWindow;
import com.tianzeculture.stagebao.util.PhotoUtils;
import com.tianzeculture.stagebao.util.Util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/5/24 0024.
 * 完善个人信息
 */

public class PerfectPersonInfoActivity extends BaseActivity implements CityPickerPopWindow.CityPickListener {

    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;

    SexDialog sexDialog = null;
    PhotoDialog photoDialog = null;
    ChoiceJobDialog choiceJobDialog = null;

    @BindView(R.id.layout_root)
    LinearLayout rootLayout;
    //    @BindView(R.id.tvTitle)
//    TextView tvTitle;
    @BindView(R.id.ivPhoto)
    ImageView ivPhoto;
    @BindView(R.id.edtNickName)
    EditText edtNickName;
    @BindView(R.id.tvSex)
    TextView tvSex;
    @BindView(R.id.tvAddress)
    TextView tvAddress;
    @BindView(R.id.tvJob)
    TextView tvJob;
    //    @BindView(R.id.tvRight)
//    TextView tvRight;
    @BindView(R.id.btnSubmit)
    Button btnSubmit;

    String imageUrl;

    int sex = -1;//-1未选 0女 1男
    @Request
    UserRestUsage userRestUsage = null;
    private int updateUserInfo = 101;//更新个人信息

    @Override
    public void initUI() {
        super.initUI();
        StageBaoApplication.addActivity(this);

//        tvTitle.setText(getString(R.string.perfect_personal));
//        tvRight.setVisibility(View.VISIBLE);//标题栏右侧按钮显示
    }

//    @OnClick(R.id.tvRight)
//    public void nextStep(View view) {
//        //跳过
//        startActivity(new Intent(this, LoginActivity.class));
//        finish();
//    }


    @OnClick(R.id.ivPhoto)
    public void choicePhoto(View view) {
        PhotoDialog photoDialog = new PhotoDialog(PerfectPersonInfoActivity.this);
        photoDialog.setOnSelectClickListener(new PhotoDialog.OnSelectClickListener() {
            @Override
            public void onOk(boolean isTakePic) {
                if (isTakePic) {
                    autoObtainCameraPermission();
                } else {
                    autoObtainStoragePermission();
                }


            }

            @Override
            public void onCancel() {

            }
        });
        photoDialog.show();
    }

    @OnClick(R.id.tvSex)
    public void choiceSex(View view) {
        sexDialog = new SexDialog(this);
        sexDialog.setOnSelectClickListener(new SexDialog.OnSelectClickListener() {
            @Override
            public void onOk(boolean isMale) {
                if (isMale) {
                    tvSex.setText("男");
                    sex = 1;
                } else {
                    tvSex.setText("女");
                    sex = 0;
                }
            }

            @Override
            public void onCancel() {

            }
        });
        sexDialog.show();
    }

    @OnClick(R.id.tvAddress)
    public void selectAddress(View view) {
        if (Util.isFastClick()) {
            //判断软键盘是否打开，为true则关闭，否则不处理
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            boolean isOpen = imm.isActive();
            if (isOpen) {
                Util.closeKeyboard(PerfectPersonInfoActivity.this);
            }
            //城市选择弹出框
            CityPickerPopWindow mPopWindow = new CityPickerPopWindow(this);
            mPopWindow.showPopupWindow(rootLayout);
            mPopWindow.setCityPickListener(this);
        }
    }

    @OnClick(R.id.tvJob)
    public void choiceJob(View view) {
        choiceJobDialog = new ChoiceJobDialog(this);
        choiceJobDialog.setChoiceState(0);//未选择
        choiceJobDialog.setOnSelectClickListener(new ChoiceJobDialog.OnSelectClickListener() {
            @Override
            public void onOk(int state) {
                if (state == 1) {
                    tvJob.setText("艺人");
                } else {
                    tvJob.setText("商家");
                }

            }

            @Override
            public void onCancel() {

            }
        });
        choiceJobDialog.show();
    }

    @OnClick(R.id.btnSubmit)
    public void submit(View view) {
        if (null == imageUrl) {
            ToastUtil.showShort(this, "请选择头像");
            return;
        } else if ("".equals(edtNickName.getText().toString().trim())) {
            ToastUtil.showShort(this, "请输入昵称");
            return;
        } else if (sex == -1) {
            ToastUtil.showShort(this, "请选择性别");
            return;
        } else if ("".equals(tvAddress.getText().toString().trim())) {
            ToastUtil.showShort(this, "请选择地区");
            return;
        } else {
            showProgressDialog();
            Bitmap bitmap = BitmapFactory.decodeFile(imageUrl);
            String string = bitmap2StrByBase64(bitmap);
            bitmap.recycle();
            userRestUsage.updateUserInfo(updateUserInfo, string, edtNickName.getText().toString().trim()
                    , sex, tvAddress.getText().toString().trim());
        }
    }

    @Override
    public void refreshUI(int taskId, MSG msg) {
        super.refreshUI(taskId, msg);
        if (taskId == updateUserInfo) {
            if (msg.getData()) {
//                User user = (User) msg.getObj();
//                if (!"".equals(user.getUid())) {
//                    Util.Uid = user.getUid();
//                }
//                if (!"".equals(user.getUserId()))
//                    Util.UserId = user.getUserId();
//                Util.Token = user.getToken();
//                Util.JOB = user.getUserType();
                ToastUtil.showShort(this, "提交成功");
                startActivity(new Intent(this, LoginActivity.class));
            }
            dismissProgressDialog();
        }
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_perfect_person_info;
    }


    /**
     * 自动获取相机权限
     */
    private void autoObtainCameraPermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                ToastUtil.showShort(this, "您已经拒绝过一次");
            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
        } else {//有权限直接调用系统相机拍照
            if (hasSdcard()) {
                imageUri = Uri.fromFile(fileUri);
                //通过FileProvider创建一个content类型的Uri
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(PerfectPersonInfoActivity.this, "com.tianzeculture.stagebao.FileProvider", fileUri);
                }
                PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
            } else {
                ToastUtil.showShort(this, "设备没有SD卡！");
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            //调用系统相机申请拍照权限回调
            case CAMERA_PERMISSIONS_REQUEST_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        imageUri = Uri.fromFile(fileUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            imageUri = FileProvider.getUriForFile(PerfectPersonInfoActivity.this, "com.tianzeculture.stagebao.FileProvider", fileUri);//通过FileProvider创建一个content类型的Uri
                        PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                    } else {
                        ToastUtil.showShort(this, "设备没有SD卡！");
                    }
                } else {

                    ToastUtil.showShort(this, "请允许打开相机！！");
                }
                break;


            }
            //调用系统相册申请Sdcard权限回调
            case STORAGE_PERMISSIONS_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                } else {

                    ToastUtil.showShort(this, "请允许打操作SDCard！！");
                }
                break;
            default:
        }
    }

    private static final int OUTPUT_X = 480;
    private static final int OUTPUT_Y = 480;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //拍照完成回调
                case CODE_CAMERA_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                //访问相册完成回调
                case CODE_GALLERY_REQUEST:
                    if (hasSdcard()) {
                        cropImageUri = Uri.fromFile(fileCropUri);
                        Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                            com.tianzeculture.stagebao.FileProvider
                            newUri = FileProvider.getUriForFile(this, "com.tianzeculture.stagebao.FileProvider", new File(newUri.getPath()));
                        }
                        PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    } else {
                        ToastUtil.showShort(this, "设备没有SD卡！");
                    }
                    break;
                case CODE_RESULT_REQUEST:
                    Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                        showImages(bitmap);
                        imageUrl = cropImageUri.getPath();
                    }
                    break;
                default:
            }
        }
    }


    /**
     * 自动获取sdk权限
     */

    private void autoObtainStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
        } else {
            PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
        }

    }

    private void showImages(Bitmap bitmap) {
        ivPhoto.setImageBitmap(bitmap);
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }


    @Override
    public void pickValue(String value) {
        if (value.length() > 0)
            tvAddress.setText(value.substring(value.indexOf("-") + 1, value.length()));
    }

    /**
     * 关闭软键盘
     */
    public void closrKeyboard() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        ToastUtil.showShort(this, "请完善资料");
        return true;
    }


    /**
     * 处理图片并上传
     *
     * @param imgPath
     */
    private void handleImg(String imgPath) {
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        Map<String, String> params = new HashMap<>();
        params.put("photoImgFile", bitmap2StrByBase64(bitmap));
        bitmap.recycle();

//        userRestUsage.updateUserInfo(updateHeader, params);
    }

    /**
     * 通过Base32将Bitmap转换成Base64字符串
     *
     * @param bit
     * @return
     */
    public String bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return
//                "data:image/" + type + ";base64," +
                Base64.encodeToString(bytes, Base64.DEFAULT);
    }

}
